package com.yequan.nio.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author : Administrator
 * @date : 2020/7/2
 */
public class BlockServer {

    public static void main(String[] args) throws IOException {
        long startTime = System.currentTimeMillis();
        ServerSocketChannel server = ServerSocketChannel.open();
        server.bind(new InetSocketAddress(6666));
        SocketChannel client = server.accept();
        FileChannel fileChannel = FileChannel.open(Paths.get("F:\\Temp\\nio\\psdb.rar"), StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (client.read(buffer) != -1) {
            buffer.flip();
            fileChannel.write(buffer);
            buffer.clear();
        }
        long consumeTime = System.currentTimeMillis() - startTime;
        buffer.put(("接收完成,耗时:" + consumeTime + " ms").getBytes());
        buffer.flip();
        client.write(buffer);
        buffer.clear();
        client.close();
        fileChannel.close();
        server.close();
    }

}
